﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	TabContainer.cs
//  Developer:	Solomatov Igor
//  Created:	14.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Smart.Common.WebControls
{
	[Localizable(false), ToolboxData("<{0}:TabContainer runat=server></{0}:TabContainer>")]
	public class TabContainer : CompositeControl, IPostBackEventHandler
	{
		private static readonly object TabChangedEventKey = new Object();

		[Category("Behavior")]
		public event EventHandler TabChanged
		{
			add { Events.AddHandler(TabChangedEventKey, value); }
			remove { Events.RemoveHandler(TabChangedEventKey, value); }
		}

		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("redmond")]
		[Localizable(false)]
		public string Theme
		{
			get { return (string)ViewState["Theme"] ?? string.Empty; }
			set { ViewState["Theme"] = value; }
		}

		[DefaultValue((string)null), MergableProperty(false)]
		[PersistenceMode(PersistenceMode.InnerProperty)]
		public TabPageCollection Tabs
		{
			get
			{
				var c = ViewState["tabs"] as TabPageCollection;

				if (c == null)
					ViewState["pg"] = c = new TabPageCollection();

				return c;
			}
		}

		public HiddenField TabState;

		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			TabState = new HiddenField { ID = ID + "state" };
			Controls.Add(TabState);
		}

		protected virtual string GetTabStateInfo()
		{
			if (TabState.Value == "" && !DesignMode)
				TabState.Value = Page.Request[TabState.UniqueID];

			return TabState.Value;
		}

		/// <summary>
		/// Return index of current tab
		/// </summary>
		public int CurrentTab
		{
			get
			{
				var info = GetTabStateInfo();

				if (info.IsNullOrEmpty())
					return -1;

				var ia = info.Split(';');

				return ia[0].SToInt(-1);
			}
			set { TabState.Value = string.Format("{0};{1}", value, PreviousTab); }
		}

		/// <summary>
		/// Return index of previous tab
		/// </summary>
		public int PreviousTab
		{
			get
			{
				var info = GetTabStateInfo();

				if (info.IsNullOrEmpty())
					return -1;

				var ia = info.Split(';');

				if (ia.Length < 2)
					return -1;

				return ia[1].SToInt(-1);
			}
		}

		protected override void OnPreRender(EventArgs e)
		{
			ClientAssets.RegisterJQuery(false, false, true, Theme, false, null, false, null);

			var tabList = new StringBuilder();

			foreach (TabPage tab in Tabs)
			{
				if (tabList.Length > 0)
					tabList.Append(',');

				tabList.AppendFormat(
					@"{{id:'#{0}',title:'{1}',conf:'',postback:false}}",
					tab.ClientID,
					tab.Title.EncodeJS("'"));
			}

			var js = string.Format(
				@"$('#{0}').Tabs({{tabs: [{1}],postback:""{2}"",inp:'#{3}'});",
				ClientID,
				tabList,
				Page.ClientScript.GetPostBackEventReference(this, "tpb"),
				TabState.ClientID);

			ScriptManager.RegisterStartupScript(this, GetType(), "tc" + ClientID, js, true);

			base.OnPreRender(e);
		}

		public virtual void RaisePostBackEvent(string eventArgument)
		{
			if (!eventArgument.EqIC("tpb"))
				throw new NotSupportedException();

			var eh = (EventHandler)Events[TabChangedEventKey];

			if (eh != null)
				eh(this, EventArgs.Empty);
		}
	}
}